package com.caigou.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
    public static String getCookie(HttpServletRequest request, String cookieName){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie: cookies){
                if (cookie.getName().equals(cookieName)){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static void writeCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String value){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            boolean isExits = false;
            String valueStr = "";
            for (Cookie cookie: cookies){
                if (cookie.getName().equals(cookieName)){
                    isExits = true;
                    valueStr = cookie.getValue();
                    break;
                }
            }
            Cookie cookie;
            if (isExits){
                cookie = new Cookie(cookieName,valueStr+value+"%2C");
                cookie.setPath("/");
                cookie.setDomain("caigou2003.com");
                cookie.setMaxAge(-1);
                response.addCookie(cookie);
            } else {
                cookie = new Cookie(cookieName,"%2C"+value+"%2C");
                cookie.setPath("/");
                cookie.setDomain("caigou2003.com");
                cookie.setMaxAge(-1);
                response.addCookie(cookie);
            }
        } else {
            Cookie cookie = new Cookie(cookieName,"%2C"+value+"%2C");
            cookie.setPath("/");
            cookie.setDomain("caigou2003.com");
            cookie.setMaxAge(-1);
            response.addCookie(cookie);
        }
    }
}
